Golang : Set or add headers for many or different handlers
Problem :
In Golang, setting headers can be done easily with the Set() method.
At the moment, you are setting headers for each individual handler in such as manner :
func handlerA(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler B."))
}
Instead of setting header for each individual handler manually, you want to use a function to set the headers.
NOTE : This method can apply to Add headers as well
Solution :
Create a common SetHeaders()
function that will write to http.ResponseWriter. For example :
func SetHeaders(w http.ResponseWriter) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
}
func handlerA(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler B."))
}
See also : Golang : How to Set or Add Header http.ResponseWriter?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+29.2k Golang : Get first few and last few characters from string
+9.2k Golang : Intercept and compare HTTP response code example
+4.7k JavaScript : Rounding number to decimal formats to display currency
+10.7k Golang : Simple File Server
+10k Golang : Function wrapper that takes arguments and return result example
+6.1k Golang : Function as an argument type example
+5.5k Unix/Linux/MacOSx : How to remove an environment variable ?
+9.8k Golang : Resumable upload to Google Drive(RESTful) example
+24.1k Golang : Fix type interface{} has no field or no methods and type assertions example
+5.3k Python : Create Whois client or function example
+14.1k Golang : Compress and decompress file with compress/flate example
+7.1k Golang : How to call function inside template with template.FuncMap